<template>
  <div class="article-container">
    <el-row>
      <el-col :span="22" :offset="1">
        <!--卡片-->
        <card class="table-container" cardName="标签列表" :scalable="false">
          <!--工具栏-->
          <tool-bar slot="tool" @emptyQuery="emptyQuery" @receiveKeyword="receiveKeyword" class="toolbar">
            <div slot="buttonContainer" class="button-all-container">
              <!--工具栏上第一个按钮-->
              <div class="btn-container" v-if="hasPermission('tag:insert')">
                <el-button class="toolbar-button" @click="openSaveTagModal">
                  <i class="el-icon-circle-plus-outline"></i>
                  新增标签
                </el-button>
              </div>
              <!--工具栏上第二个按钮-->
              <div class="btn-container" v-if="hasPermission('tag:delete')">
                <el-button class="toolbar-button" @click="deleteMultiTags">
                  <i class="iconfont icon-shanchu"></i>
                  批量删除
                </el-button>
              </div>
            </div>
            <div slot="customContainer" class="custom-container">
              <el-select v-model="query.cid" class="category-select" placeholder="分类查询">
                <el-option
                  v-for="item in categoryData"
                  :key="item.id"
                  :label="item.categoryName"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
          </tool-bar>

          <!--卡片里的内容-->
          <el-table
            slot="content"
            ref="tagTable"
            :data="tagData"
            stripe
            border
            :fit="true"
            style="width: 100%"
            @select="selectTag"
            @select-all="selectTag"
            :key="Date.now()">
            <el-table-column
              align="center"
              type="selection"
              min-width="30">
            </el-table-column>
            <el-table-column
              prop="tagName"
              label="标签名称"
              min-width="80">
            </el-table-column>
            <el-table-column
              prop="categoryName"
              label="所属分类"
              min-width="80">
            </el-table-column>
            <el-table-column
              prop="description"
              label="描述"
              min-width="350">
            </el-table-column>
            <el-table-column
              align="center"
              prop="sort"
              label="排序"
              min-width="50">
            </el-table-column>
            <el-table-column
              align="center"
              prop="usable"
              label="启用"
              min-width="60">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.usable"
                  active-color="#409EFF"
                  :active-value="1"
                  :inactive-value="0"
                  :disabled="!hasPermission('tag:update')"
                  @change="changeUsable(scope.row)">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column
              prop="updateTime"
              label="更新时间"
              min-width="120">
            </el-table-column>
            <el-table-column
              label="操作"
              min-width="150">
              <template slot-scope="scope">
                <span v-if="!hasPermission('tag:update') && !hasPermission('tag:delete')">-</span>
                <el-button
                  type="primary"
                  class="editBtn"
                  size="small"
                  v-if="hasPermission('tag:update')"
                  @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button
                  size="small"
                  type="danger"
                  v-if="hasPermission('tag:delete')"
                  @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </card>
      </el-col>
    </el-row>
    <pagination @getCurrentPage="getCurrentPageFromPagination" :total="total"></pagination>
    <save-tag-template 
      :tagFromParent="tagForUpdate" 
      @reloadTable="loadTableForTag" 
      ref="saveTagTemplate"></save-tag-template>
  </div>
</template>

<script>
  import Card from 'components/common/card/Card';
  import Pagination from 'components/common/pagination/Pagination';
  import ToolBar from 'components/content/toolbar/ToolBar'
  import SaveTagTemplate from './subView/SaveTagTemplate'

  import {getAllCategory} from "../../network/viewsRequest/category";
  import {getTagByPage, changeUsable, deleteByIds, getTagById} from "../../network/viewsRequest/tag";
  import {hasPermission} from "../../common/permission";

  export default {
    name: 'TagView',
    data() {
      return {
        query: {
          currentPage: 1,
          pageSize: 10,
          cid: null,
          keyword: '', // toolbar中传递过来的搜索关键字
        },
        tagData: [],
        categoryData: [],
        total: 0,
        multiSelections: [],
        tagForUpdate: {}, // 回显时传递给模态框的标签信息
      }
    },
    methods: {
      hasPermission(permission) {
        return hasPermission(permission);
      },
      /**
       * 清空查询条件
       */
      emptyQuery() {
        let currentPage = this.query.currentPage;
        let pageSize = this.query.pageSize;
        this.query = {
          keyword: '',
          cid: null,
          currentPage: currentPage,
          pageSize: pageSize,
        }
        this.loadTableForTag();
      },
      /**
       * 点击多选框时触发的方法
       * @param selection 已经选中的集合，
       * @param row 当前选中的行
       */
      selectTag(selection, row) {
        this.multiSelections = selection;
      },
      /**
       * 用户在点击分页插件时，获取用户点击到的是第几页
       */
      getCurrentPageFromPagination(page) {
        this.query.currentPage = page;
        this.loadTableForTag();
      },
      /**
       * 编辑标签
       * @param index 当前编辑分类的索引
       * @param row 当前编辑分类的那行内容
       */
      handleEdit(index, row) {
        // 1.获取该标签的信息
        getTagById(row.id).then(res => {
          if (res.code == 1) {
            this.tagForUpdate = res.data;
            // 2.打开模态框
            this.$refs.saveTagTemplate.show();
          } else {
            this.$message({
              type: 'error',
              message: res.message
            })
            this.tagForUpdate = {};
          }

        })
      },
      /**
       * 删除标签
       * @param index 需要删除分类的索引
       * @param row 需要删除分类的那行内容
       */
      handleDelete(index, row) {
        let delIds = [];
        delIds.push(row.id);
        this.deleteTags(delIds);
      },
      deleteMultiTags() {
        if (this.multiSelections.length == 0) {
          this.$message({
            type: 'error',
            message: '请选择需要进行删除的标签信息'
          });
          return;
        }
        let delIds = this.multiSelections.map(item => {
          return item.id;
        });
        this.deleteTags(delIds);
      },
      /**
       * 根据集合批量删除标签
       */
      deleteTags(ids) {
        this.$confirm('是否要删除？注意：一旦删除无法恢复', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteByIds(ids.join(",")).then(res => {
            if (res.code == 1) {
              this.$message({
                type: 'success',
                message: '删除成功！'
              });
              this.loadTableForTag();
            } else {
              this.$message({
                type: 'error',
                message: res.message
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '删除操作已经被取消'
          })
        })
      },
      /**
       * 接收子组件toolbar传递过来的搜索关键字keyword
       * @param keyword 搜索关键字
       */
      receiveKeyword(keyword) {
        this.query.keyword = keyword;
        this.query.currentPage = 1;
        this.loadTableForTag();
      },
      /**
       * 获取所有分类的信息
       */
      getAllCategory() {
        getAllCategory().then(res => {
          if (res.code == 1) {
            this.categoryData = res.data;
          } else {
            this.categoryData = [];
          }
        });
      },
      /**
       * 分页并条件查询标签的信息
       */
      loadTableForTag() {
        getTagByPage(this.query).then(res => {
          if (res.code == 1) {
            this.tagData = res.data.items;
            this.total = res.data.total;
          } else {
            this.tagData = [];
            this.total = 0;
          }
        });
      },
      /**
       * 用户点击`新增`按钮调用的方法
       */
      openSaveTagModal() {
        this.$refs.saveTagTemplate.show();
      },
      /**
       * 用户切换是否启用该标签时调用的方法
       */
      changeUsable(row) {
        changeUsable(row.id, row.usable).then(res => {
          if (res.code == 1) {
            this.$message({
              type: 'success',
              message: '操作成功！'
            })
          } else {
            this.$message({
              type: 'error',
              message: res.message
            });
            this.loadTableForTag();
          }
        })
      }
    },
    created() {
      // 获取表格中需要的标签相关的信息
      this.loadTableForTag();
      // 获取所有分类的信息
      this.getAllCategory();
    },
    components: {
      Card,
      Pagination,
      ToolBar,
      SaveTagTemplate
    }
  }
</script>

<style scoped>
  .toolbar-button {
    width: 120px;
    height: 36px;
    padding: 0 20px 0 15px;
    vertical-align: middle;
  }
  .table-container {
    width: 100%;
    height: 100%;
    position: relative;
  }

  .button-all-container {
    display: inline-block;
    vertical-align: bottom;
  }

  .custom-container {
    display: inline-block;
    margin-left: 10px
  }

  .el-card {
    margin-top: 30px;
  }
  .editBtn {
    background-color: #409EFF;
    border: 1px solid #409EFF;
    color: #fff
  }
  .el-select {
    width: 110px;
  }
  .btn-container {
    margin-right: 5px;
  }
  .category-select {
    margin-right: 5px;
  }
</style>

<style>
  .el-input__inner {
    vertical-align: middle;
    height: 36px !important;
  }

  .el-button--default:first-child i,
  .el-button--default:last-child i {
    font-size: 14px;
  }

  .el-button--default span {
    font-size: 14px !important;
  }
  .el-select-dropdown__wrap, .el-scrollbar__wrap {
    margin-bottom: 0px !important
  }
  .el-popup-parent--hidden {
    padding-right: 0px !important;
  }

  .el-table__body td {
    padding-top: 10px !important;
    padding-bottom: 10px !important;
  }

  .el-button {
    margin-left: 0px !important;
    margin-right: 10px;
  }
</style>
